<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--优惠券-->
			<view class="detail-item">
				<uni-section :title="type == 2 ? '指定发放优惠券' : '优惠券'" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
					  <uni-forms-item label="名称" name="name" required>
					    <uni-easyinput v-model="formData.name" placeholder="请输入名称" />
					  </uni-forms-item>
						<uni-forms-item label="类型" name="type" required>
					    <uni-data-select
					    	v-model="formData.type"
					    	placeholder="请选择类型"
					    	:localdata="couponTypeList"></uni-data-select>
					  </uni-forms-item>
						<uni-forms-item label="区域" name="regionCode" required>
						  <uni-data-select
						  	v-model="formData.regionCode"
						  	placeholder="请选择区域"
								:disabled="!!id"
						  	:localdata="setStore.allProvinceList"></uni-data-select>
						</uni-forms-item>
					  <uni-forms-item label="最低消费" name="minConsume" required>
					    <uni-easyinput type="number" v-model="formData.minConsume" placeholder="请输入最低消费" />
					  </uni-forms-item>
						<uni-forms-item label="抵扣金额" name="discountMoney" required>
						  <uni-easyinput type="number" v-model="formData.discountMoney" placeholder="请输入抵扣金额" />
						</uni-forms-item>
						<uni-forms-item label="发放顾客" name="customer" v-if="type == 2">
							<view class="tags main-flex" v-if="id">
								<up-tag
									class="tags-item"
									:text="item"
									size="mini"
									v-for="(item, index) in couponRecordListInfo" :key="index"></up-tag>
							</view>
							<view v-else class="tags main-flex">
								<up-tag
									class="tags-item"
									:text="`${item.customerName}(${item.customerId})`"
									size="mini"
									v-for="item in formData.couponRecordList" :key="item.customerId"></up-tag>
								<up-tag class="tags-item" :disabled="id" text="选择" size="mini" @click="openCustomer">
									<template v-slot:icon>
										<up-icon name="plus" :disabled="id" color="#FFFFFF" size="16"></up-icon>
									</template>
								</up-tag>
								<up-tag class="tags-item" text="清空" size="mini" type="error" @click="clearCustomer">
									<template v-slot:icon>
										<up-icon name="trash" color="#FFFFFF" size="16"></up-icon>
									</template>
								</up-tag>
								
							</view>
						</uni-forms-item>
						<uni-forms-item label="发布总量" name="totalNumber" required>
						  <uni-easyinput type="number" :disabled="type==2" v-model="formData.totalNumber" placeholder="请输入发布总量" />
						</uni-forms-item>
						<uni-forms-item label="开始时间" name="startTime" required>
							<uni-datetime-picker type="datetime" placeholder="请选择有效期开始时间" v-model="formData.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间" name="endTime" required>
							<uni-datetime-picker type="datetime" placeholder="请选择有效期结束时间" v-model="formData.endTime"/>
						</uni-forms-item>
						<uni-forms-item label="主体色" name="backColor" v-if="info.id">
							<ty-color-picker @confirm="confirmColor" :color="info.backColor" :defaultColor="info.backColor"></ty-color-picker>
							<uni-easyinput style="display: none;" v-model="formData.backColor" placeholder="请选择主体色" />
						</uni-forms-item>
						<uni-forms-item label="主体色" name="backColor" v-else>
							<ty-color-picker @confirm="confirmColor" ></ty-color-picker>
							<uni-easyinput style="display: none;" v-model="formData.backColor" placeholder="请选择主体色" />
						</uni-forms-item>
					  <uni-forms-item label="广告语" name="ad">
					    <uni-easyinput v-model="formData.ad" placeholder="请输入广告语" />
					  </uni-forms-item>
					  <uni-forms-item label="背景图" name="backImg">
							<up-upload
								:fileList="fileList"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="1"
								></up-upload>
					    <uni-easyinput style="display: none;" v-model="formData.backImg" placeholder="请输入门店照片" />
					  </uni-forms-item>
					  <uni-forms-item label="叠加使用" name="accumulationFlag">
					    <view class="search-form-checkbox main-flex">
								<up-switch
									v-model="formData.accumulationFlag"
									:active-value="1"
									:inactive-value="0"
									disabled
									inactive-color="#ff4949"
									active-color="#13ce66"></up-switch>
					    </view>
					  </uni-forms-item>
						<uni-forms-item label="积分商城" name="saleFlag">
						  <view class="search-form-checkbox main-flex">
						  	<up-switch
						  		v-model="formData.saleFlag"
						  		:active-value="1"
						  		:inactive-value="0"
									:disabled="type==2"
						  		inactive-color="#ff4949"
						  		active-color="#13ce66"></up-switch>
						  </view>
						</uni-forms-item>
						<uni-forms-item label="积分兑换" name="integralValue" v-if="formData.saleFlag">
						  <uni-easyinput type="number" v-model="formData.integralValue" placeholder="请输入积分兑换" />
						</uni-forms-item>
					  <uni-forms-item label="备注" name="remark">
					    <uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入备注" />
					  </uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
		
		<ty-customer-picker
			@close="closeCustomer"
			@change="changeCustomer"
			:showCustomer="showCustomer"></ty-customer-picker>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { timeFormat } from 'uview-plus'
import { couponAdd, couponDetail } from "@/api/erp_api/coupon"
import { upload } from "@/api/system/common"
import { couponTypeList } from '@/utils/config.js'
import { customer } from "@/api/erp_api/customer"
import tyColorPicker from '@/components/ty-color-picker/ty-color-picker.vue'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	const type = ref('')
	onLoad((option) => {
		type.value = option.type ? option.type : 1
		if (option.id) {
			uni.setNavigationBarTitle({
				title: type.value == 2 ? '修改指定发放优惠券' : '修改优惠券'
			})
			id.value = option.id
			getDetail()
		} else {
			uni.setNavigationBarTitle({
				title: type.value == 2 ? '添加指定发放优惠券' : '添加优惠券'
			})
		}
	})
	
	// 颜色选择
	const confirmColor = (e) => {
		formData.value.backColor = e
	}
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		couponDetail(params).then(res => {
			info.value = res.data || {}
			formData.value = {
				name: res.data.name,
				minConsume: res.data.minConsume,
				backColor: res.data.backColor,
				backImg: res.data.backImg,
				ad: res.data.ad,
				discountMoney:  res.data.discountMoney,
				remark: res.data.remark,
				accumulationFlag: res.data.accumulationFlag,
				integralValue: res.data.integralValue,
				saleFlag: res.data.saleFlag,
				totalNumber: res.data.totalNumber,
				type: res.data.type,
				endTime: res.data.endTime,
				startTime: res.data.startTime
			}
			fileList.value = res.data.backImg ? res.data.backImg.split(',').map(item => {
				return {
					status: 'success',
					message: '上传成功',
					url: item,
					type: 'image'
				}
			}) : []
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	const couponRecordListInfo = computed(() => {
		return info.value.giveOut ? info.value.giveOut.split(',').filter(item => item) : []
	})
	
	// 图片上传
	const fileList = ref([])
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value.splice(event.index, 1)
		formData.value.backImg = fileList.value.map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value.length
	  lists.map((item) => {
	    fileList.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[fileListLen]
	    fileList.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		formData.value.backImg = fileList.value.map(item => item.url).join(',')
	};
	
	// 发放顾客
	const showCustomer = ref(false)
	const openCustomer = () => {
		showCustomer.value = true
	}
	const closeCustomer = () => {
		showCustomer.value = false
	}
	
	// 清空
	const clearCustomer = () => {
		formData.value.couponRecordList = []
		formData.value.totalNumber = ''
	}
	
	const changeCustomer = (e) => {
		const chooseCustomerId = formData.value.couponRecordList.map(item => item.customerId)
		const customerList = e.filter(item => chooseCustomerId.indexOf(item.id) === -1)
		formData.value.couponRecordList = formData.value.couponRecordList.concat(customerList.map(item => {
			return {
				customerId: item.id,
				customerName: item.name
			}
		}))
		formData.value.totalNumber = e.length
	}
	
	// form表单数据
	const formData = ref({
		name: '',
		minConsume: '',
		backColor: '',
		backImg: '',
		ad: '',
		discountMoney: '',
		couponRecordList: [],
		remark: '',
		accumulationFlag: 0,
		integralValue: '',
		saleFlag: 0,
		totalNumber: '',
		type: '',
		endTime: '',
		startTime: '',
		regionCode: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		name: {
			rules: [{ required: true, errorMessage: '请输入姓名' }]
		},
		regionCode: {
			rules: [{ required: true, errorMessage: '请选择区域' }]
		},
		type: {
			rules: [{ required: true, errorMessage: '请选择类型' }]
		},
		minConsume: {
			rules: [{ required: true, errorMessage: '请输入最低消费' }]
		},
		totalNumber: {
			rules: [{ required: true, errorMessage: '请输入发布总量' }]
		},
		startTime: {
			rules: [{ required: true, errorMessage: '请选择开始时间' }]
		},
		endTime: {
			rules: [{ required: true, errorMessage: '请选择结束时间' }]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			isSubmit.value = true
			const params = { ...formData.value }
			if (id.value) {
				params.id = id.value
			} else {
				params.subType = type.value == 2 ? 1 : 0
				params.giveOut = formData.value.couponRecordList.map(item => `${item.customerName}(${item.customerId})`).join(',')
			}
			couponAdd(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch(err => {
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			name: '',
			minConsume: '',
			backColor: '',
			backImg: '',
			ad: '',
			discountMoney: '',
			couponRecordList: [],
			remark: '',
			accumulationFlag: 0,
			integralValue: '',
			saleFlag: 0,
			totalNumber: '',
			type: '',
			endTime: '',
			startTime: '',
			regionCode: ''
		}
	}
</script>

<style scoped lang="scss">
	.tags {
		flex-wrap: wrap;
		min-height: 100%;
		margin: 0 -4px;
		&-item {
			margin: 4px;
		}
	}
	.search {
		margin-top: 0;
	}
</style>
